<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="日志ID" prop="logId">
        <el-input v-model="queryParams.logId" placeholder="请输入日志ID" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->

      <el-form-item label="农业规则">
        <el-select v-model="queryParams.ruleId" placeholder="请选择农业规则" clearable filterable @keyup.enter="handleQuery"
          style="width: 200px">
          <el-option v-for="item in rulesOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="定时器">
        <el-select v-model="queryParams.timerId" placeholder="请选择定时器" clearable filterable @keyup.enter="handleQuery"
          style="width: 200px">
          <el-option v-for="item in timersOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="触发预警" prop="isTriggered">
        <el-select v-model="queryParams.isTriggered" placeholder="请选择是否触发预警" clearable filterable @change="handleQuery"
          @keyup.enter="handleQuery">
          <el-option label="触发预警" value="true" />
          <el-option label="正常状态" value="false" />
        </el-select>
      </el-form-item>


      <!-- <el-form-item label="模型ID" prop="modelId">
        <el-input v-model="queryParams.modelId" placeholder="请输入模型ID" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="发生概率" prop="probability">
        <el-input v-model="queryParams.probability" placeholder="请输入发生概率" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <!-- <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['system:ruleswarnlog:remove']">
            删除
          </el-button> -->
          <el-button type="warning" plain icon="Download" @click="handleExport"
            v-hasPermi="['system:ruleswarnlog:export']">
            导出
          </el-button>
          <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" /> -->
        </div>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['system:ruleswarnlog:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:ruleswarnlog:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:ruleswarnlog:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:ruleswarnlog:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="ruleswarnlogList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="序号" align="center" prop="logId" /> -->
      <el-table-column label="预警时间" align="center" prop="createTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="定时器名称" align="center" prop="timerName" />
      <el-table-column label="规则名称" align="center" prop="ruleName" />
      <el-table-column label="农业规则" align="center" prop="ruleSnapshot" width="260" />
      <el-table-column label="环境快照" align="center" prop="envSnapshot" width="250">
        <template #default="scope">
          <div style="max-width: 230px; white-space: normal; word-break: break-word; overflow: hidden;">
            {{
              (scope.row.envSnapshot && scope.row.envSnapshot.length > 80)
                ? scope.row.envSnapshot.substring(0, 80) + '...'
                : scope.row.envSnapshot || ''
            }}
          </div>
        </template>
      </el-table-column>


      <el-table-column label="触发预警" align="center" prop="isTriggered" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isTriggered === 'true' ? 'danger' : 'success'" effect="dark"
            style="cursor: default;">
            {{ scope.row.isTriggered === 'true' ? '触发预警' : '正常状态' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="防治建议" align="center" prop="modelSuggestion" width="200">
        <template #default="scope">
          <div style="max-width: 230px; white-space: normal; word-break: break-word; overflow: hidden;">
            {{
              scope.row.modelSuggestion
                ? (scope.row.modelSuggestion.length > 30
                  ? scope.row.modelSuggestion.substring(0, 30) + '...'
                  : scope.row.modelSuggestion)
                : '无'
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订阅用户" align="center" prop="userName" width="100" />
      <el-table-column label="手机号" align="center" prop="phone" width="130">
        <template #default="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>

      <el-table-column label="发生概率" align="center" prop="probability" width="100">
        <template #default="scope">
          <span>{{ scope.row.probability }}%</span>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:ruleswarnlog:edit']">详情</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:ruleswarnlog:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 规则预警日志对话框详情 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ruleswarnlogRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="定时器ID" prop="timerId">
      <el-input v-model="form.timerId" placeholder="请输入定时器ID" readonly />
    </el-form-item>
    <el-form-item label="订阅记录" prop="subId">
      <el-input v-model="form.subId" placeholder="请输入订阅记录ID" readonly />
    </el-form-item> -->
        <!-- <el-form-item label="规则ID" prop="ruleId">
      <el-input v-model="form.ruleId" placeholder="请输入农业规则ID" readonly/>
    </el-form-item> -->

        <el-form-item label="农业规则" prop="ruleSnapshot">
          <div style="white-space: pre-wrap; word-break: break-word; max-width: 400px; min-height: 60px;">
            {{ form.ruleSnapshot }}
          </div>
        </el-form-item>

        <el-form-item label="环境快照" prop="envSnapshot">
          <div
            style="white-space: pre-wrap; word-break: break-word; max-width: 400px; min-height: 60px; line-height: 1.6;">
            {{ form.envSnapshot }}
          </div>
        </el-form-item>

        <el-form-item label="模型建议" prop="modelSuggestion">
          <div
            style="white-space: pre-wrap; word-break: break-word; max-width: 400px; min-height: 60px; line-height: 1.6;">
            {{ form.modelSuggestion }}
          </div>
        </el-form-item>


        <!-- <el-form-item label="触发预警" prop="isTriggered">
      <el-input v-model="form.isTriggered" placeholder="请输入是否触发预警" readonly />
    </el-form-item>
    <el-form-item label="模型" prop="modelId">
      <el-input v-model="form.modelId" placeholder="请输入模型ID" readonly />
    </el-form-item> -->



        <!-- <el-form-item label="发生概率" prop="probability">
      <el-input v-model="form.probability" placeholder="请输入发生概率" readonly />
    </el-form-item> -->
      </el-form>
    </el-dialog>


  </div>
</template>

<script setup name="Ruleswarnlog">
import { listRuleswarnlog, getRuleswarnlog, delRuleswarnlog } from "@/api/agriculture/znjc/ruleswarnlog"
import { getTimers, listTimers } from "@/api/agriculture/znjc/timers"
import { getRules, listRules } from "@/api/agriculture/znjc/rules"
import { ref, reactive, toRefs, onMounted } from 'vue'
import { getUsersub } from "@/api/agriculture/znjc/usersub"

import { getUser } from "@/api/system/user"

const timersOptions = ref([])
const rulesOptions = ref([])
const timerMap = ref(new Map())
const rulesMap = ref(new Map())


const { proxy } = getCurrentInstance()

const ruleswarnlogList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    logId: null,
    timerId: null,
    subId: null,
    ruleId: null,
    ruleSnapshot: null,
    envSnapshot: null,
    isTriggered: null,
    modelId: null,
    modelSuggestion: null,
    probability: null,
    createTime: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)
const userIdMap = ref(new Map())
const userNameMap = ref(new Map())
const userPhoneMap = ref(new Map())



/** 查询规则预警日志列表 */
async function getList() {
  loading.value = true
  try {
    const response = await listRuleswarnlog(queryParams.value)
    ruleswarnlogList.value = response.rows
    total.value = response.total

    await loadNames()    // 加载定时器和规则名称
    await loadUserInfo() // 加载用户ID和用户名信息
  } finally {
    loading.value = false
  }
}



// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    logId: null,
    timerId: null,
    subId: null,
    ruleId: null,
    ruleSnapshot: null,
    envSnapshot: null,
    isTriggered: null,
    modelId: null,
    modelSuggestion: null,
    probability: null,
    createTime: null
  }
  proxy.resetForm("ruleswarnlogRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.logId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// /** 新增按钮操作 */
// function handleAdd() {
//   reset()
//   open.value = true
//   title.value = "添加规则预警日志"
// }

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _logId = row.logId || ids.value
  getRuleswarnlog(_logId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "规则预警日志详情"
  })
}

// /** 提交按钮 */
// function submitForm() {
//   proxy.$refs["ruleswarnlogRef"].validate(valid => {
//     if (valid) {
//       if (form.value.logId != null) {
//         updateRuleswarnlog(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功")
//           open.value = false
//           getList()
//         })
//       } else {
//         addRuleswarnlog(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功")
//           open.value = false
//           getList()
//         })
//       }
//     }
//   })
// }

/** 删除按钮操作 */
function handleDelete(row) {
  const _logIds = row.logId || ids.value
  proxy.$modal.confirm('是否确认删除规则预警日志编号为"' + _logIds + '"的数据项？').then(function () {
    return delRuleswarnlog(_logIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/ruleswarnlog/export', {
    ...queryParams.value
  }, `ruleswarnlog_${new Date().getTime()}.xlsx`)
}


async function loadNames() {
  const promises = ruleswarnlogList.value.map(async item => {
    // 定时器名称
    if (item.timerId) {
      if (timerMap.value.has(item.timerId)) {
        item.timerName = timerMap.value.get(item.timerId)
      } else {
        try {
          const res = await getTimers(item.timerId)
          const name = res.data?.timerName || '未知定时器'
          timerMap.value.set(item.timerId, name)
          item.timerName = name
        } catch {
          item.timerName = '查询失败'
        }
      }
    } else {
      item.timerName = '无定时器ID'
    }
    // 农业规则名称
    if (item.ruleId) {
      if (rulesMap.value.has(item.ruleId)) {
        item.ruleName = rulesMap.value.get(item.ruleId)
      } else {
        try {
          const res = await getRules(item.ruleId)
          const name = res.data?.ruleName || '未知规则'
          rulesMap.value.set(item.ruleId, name)
          item.ruleName = name
        } catch {
          item.ruleName = '查询失败'
        }
      }
    } else {
      item.ruleName = '无规则ID'
    }
  })

  await Promise.all(promises)
}
// 加载定时器列表数据
async function loadTimers() {
  try {
    const res = await listTimers({ pageNum: 1, pageSize: 9999 })
    timersOptions.value = res.rows.map(item => ({
      label: item.timerName,
      value: item.timerId
    }))
  } catch (e) {
    timersOptions.value = []
  }
}
// 加载农业规则列表数据
async function loadRules() {
  try {
    const res = await listRules({ pageNum: 1, pageSize: 9999 })
    rulesOptions.value = res.rows.map(item => ({
      label: item.ruleName,
      value: item.ruleId
    }))
  } catch (e) {
    rulesOptions.value = []
  }
}
// 组件挂载时请求列表数据
onMounted(() => {
  loadTimers()
  loadRules()
})


async function loadUserInfo() {
  const promises = ruleswarnlogList.value.map(async item => {
    if (item.subId) {
      // 1. 获取用户ID
      if (userIdMap.value.has(item.subId)) {
        item.userId = userIdMap.value.get(item.subId)
      } else {
        try {
          const res = await getUsersub(item.subId)
          const userId = res.data?.userId || '未知用户ID'
          userIdMap.value.set(item.subId, userId)
          item.userId = userId
        } catch (error) {
          item.userId = '查询失败'
        }
      }

      // 2. 获取用户信息（用户名 + 手机号）
      if (item.userId && item.userId !== '未知用户ID' && item.userId !== '查询失败') {
        // 如果已缓存用户名和手机号
        const hasName = userNameMap.value.has(item.userId)
        const hasPhone = userPhoneMap.value.has(item.userId)

        if (hasName && hasPhone) {
          item.userName = userNameMap.value.get(item.userId)
          item.phone = userPhoneMap.value.get(item.userId)
        } else {
          try {
            const res = await getUser(item.userId)
            console.log('用户信息:', res.data)

            const data = res.data || {}

            const userName = data.userName || '未知用户'
            const phone = data.phonenumber || '未知手机号'  // 注意这里改成 phonenumber

            userNameMap.value.set(item.userId, userName)
            userPhoneMap.value.set(item.userId, phone)

            item.userName = userName
            item.phone = phone
          } catch (error) {
            item.userName = '查询失败'
            item.phone = '查询失败'
          }

        }
      } else {
        item.userName = '无用户ID'
        item.phone = '无用户ID'
      }
    } else {
      item.userId = '无订阅ID'
      item.userName = '无订阅ID'
      item.phone = '无订阅ID'
    }
  })

  await Promise.all(promises)
}



getList()
</script>
